<?php

namespace app\model\v1\setup;

use app\model\order\StoreOrder;
use app\model\user\User;
use app\model\v1\gift\GiftCard;
use app\model\v1\gift\GiftCardCate;
use app\model\v1\gift\GiftCardUser;
use app\model\v1\gift\RecruitLanguage;
use app\services\order\StoreOrderCreateServices;
use app\services\user\UserAddressServices;
use crmeb\traits\ModelTrait;
use think\Exception;
use think\facade\Db;
use think\Model;


class SystemAdmin extends Model
{

    use ModelTrait;

    protected $updateTime = false;
    protected $createTime = false;

    protected $hidden = [
    //    'create_time','update_time','delete_time'
    ];

    protected $table = 'eb_system_admin';



    /**
     * 菜单管理列表
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function admin_user_list($param = [])
    {
        $data['data'] = self::field("*")
            ->where(function ($query) use ($param){
                $query->where("type", 2);
                $query->where("is_del", 0);
                if(!empty($param['type'])) $query->where("type", $param["type"]);
                if(!empty($param['user_name'])) $query->where("user_name", $param["user_name"]); //登录名
                if(!empty($param['phone'])) $query->where("phone", "like","%{$param['phone']}%");  //手机号
                if(!empty($param['role_id'])) $query->where("role_id","like","%{$param['role_id']}%"); //角色
            })
            ->order('id','desc')
            ->page($param['page'], $param['limit'])
            ->select()->toArray();

        foreach ($data['data'] as $key => &$val){
            $val['role_name'] = self::getRoleName($val['role_id']);
        }

        $data['count']= self::field("*")
            ->where(function ($query) use ($param){
                $query->where("type", 2);
                $query->where("is_del", 0);
                if(!empty($param['type'])) $query->where("type", $param["type"]);
                if(!empty($param['user_name'])) $query->where("user_name", $param["user_name"]); //登录名
                if(!empty($param['phone'])) $query->where("phone", "like","%{$param['phone']}%");  //手机号
                if(!empty($param['role_id'])) $query->where("role_id","like","%{$param['role_id']}%"); //角色
            })
            ->count();

        return $data;
    }


    public static function getRoleName($ids = '')
    {
        $ids = explode(",", $ids);
        $data = SetupRole::whereIn('id', $ids)->column('group_concat(name) as name');
        return $data[0] ?? '';
    }

    public static function add_limits($param = [])
    {
        $add = [
            "pid"               => $param["pid"] ?? '',
            "name"              => $param["name"] ?? '',
            "url"               => $param["url"] ?? '',
            "sort"              => $param["sort"] ?? '',
            "url_name"          => $param["url_name"] ?? '',
            "ctime"             => date("Y-m-d H:i:s"),
        ];
        return self::insert($add);
    }



    public static function admin_user_add($param = [])
    {
        $account_find = self::where('account',$param['account'])->where("is_del", 0)->where("type", 2)->find();
        if (!empty($account_find)) Throw new Exception('account不能重复');

        $phone_find = self::where('phone',$param['phone'])->where("is_del", 0)->where("type", 2)->find();
        if (!empty($phone_find)) Throw new Exception('使用人手机号不能重复');

        $add = [
            "account"       => $param["account"], //登录名
            "pwd"           => md5($param["pwd"]), //密码
            "real_name"     => $param["real_name"], //使用人
            "phone"         => $param["phone"], //使用人手机号
            "role_id"       => $param["role_id"], //角色id
            "admin_type"    => 22,
            "type"          => 2,
            "add_time"      => time(), //创建时间
        ];

        return self::insert($add);
    }


    public static function admin_user_up($param = [])
    {
        $account_find = self::where("id","<>",$param["id"])->where('account',$param['account'])->where("type", 2)->where("is_del", 0)->find();
        if (!empty($account_find)) Throw new Exception('account不能重复');

        $phone_find = self::where("id","<>",$param["id"])->where('phone',$param['phone'])->where("type", 2)->where("is_del", 0)->find();
        if (!empty($phone_find)) Throw new Exception('使用人手机号不能重复');

        //$update["update_time"] = time();  //更新时间
        if(!empty($param["account"]))             $update["account"] = $param["account"];  //登录名
        if(!empty($param["pwd"]))                 $update["pwd"] = md5($param["pwd"]); //密码
        if(!empty($param["real_name"]))           $update["real_name"] = $param["real_name"]; //使用人
        if(!empty($param["phone"]))               $update["phone"] = $param["phone"]; //使用人手机号
        if(!empty($param["role_id"]))             $update["role_id"] = $param["role_id"]; //角色id

        return self::where("id", $param["id"])->update($update);
    }







    /**
     * 礼品卡详情
     * @param $id
     * @return GiftCard|array|mixed|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getGiftCardDetail($id)
    {
        $detail = self::field("*")
            ->with([
                "catetag" => function ($query) {
                    $query->field("id,cate_tag_name");
                }
            ])
            ->where("id", $id)
            ->whereNull("delete_time")
            ->find();
        if(!empty($detail["content"])) $detail['content'] = htmlspecialchars_decode($detail['content']);

        return $detail;
    }


    /**
     * 登录账号权限list
     * @param $role_ids
     * @return void
     */
    public static function getLimitsListData($limit_id_data = '', $pid=0)
    {
        if(empty($limit_id_data)){
            return [];
        }

        $result = [];
        //查找当前id的所有下级
        $users = SetupLimits::whereIn("id", $limit_id_data)->order("sort","desc")->where ('pid',$pid)->select()->toArray();
        if ($users){
            //循环下级id
            foreach($users as $k=> $v) {
                $result[$k] = $v;

                //递归一个一个查找下级返回数据 存入
                $userData = self::getLimitsListData($limit_id_data, $v['id']);
                if ($userData){
                    //有值 递归存入数据
                    foreach($userData as $vs) {
                        $result[$k]['son'][] = $vs;
                    }
                }
            }
        }

        return $result;
    }




    public static function getLimitsList()
    {
        $return = self::getSonsInfo(0);

        foreach ($return as $k1=> &$v1){
            foreach ($v1["son"] as $k2 => &$v2){
                if(empty($v2["son"])) unset($v2["son"]);
            }
        }
        return $return;
    }

    public static function getSonsInfo($pid=0)
    {
        $lists = [];
        $items = SetupLimits::where('pid',$pid)->order("sort","desc")->where("is_del", 0)->select()->toArray();

        foreach ($items as $item){
            $item['son'] = self::getSonsInfo($item['id']);
            $lists[] = $item;
        }

        return $lists;
    }


}